package service

import (
	"context"
	"errors"
	"fmt"
	"microstudent/proto/student"
)

var studentList []student.Student

type StudentServiceHandler struct {
}

func (h *StudentServiceHandler) Add(ctx context.Context, req *student.AddRequest, resp *student.AddResponse) error {
	var maxId int64 = 0
	for _, s := range studentList {
		if s.Id > maxId {
			maxId = s.Id
		}
	}
	maxId++
	(*req.Student).Id = maxId
	studentList = append(studentList, *req.Student)
	resp.IsSuccesses = true
	return nil
}
func (h *StudentServiceHandler) Update(ctx context.Context, req *student.UpdateRequest, resp *student.UpdateResponse) error {
	for i, s := range studentList {
		if s.Id == req.Student.Id {
			studentList[i] = *req.Student
			resp.IsSuccesses = true
			return nil
		}
	}
	resp.IsSuccesses = false
	return errors.New(fmt.Sprintf("No student with id %d", req.Student.Id))
}
func (h *StudentServiceHandler) Delete(ctx context.Context, req *student.DeleteRequest, resp *student.DeleteResponse) error {
	for i, s := range studentList {
		if s.Id == req.Id {
			studentList = append(studentList[:i], studentList[i+1:]...)
			resp.IsSuccesses = true
			return nil
		}
	}
	resp.IsSuccesses = false
	return errors.New(fmt.Sprintf("No student with id %d", req.Id))
}
func (h *StudentServiceHandler) FindOne(ctx context.Context, req *student.FindOneRequest, resp *student.FindOneResponse) error {
	for _, s := range studentList {
		if s.Id == req.Id {
			resp.Student = &s
			return nil
		}
	}
	resp.Student = nil
	return errors.New(fmt.Sprintf("No student with id %d", req.Id))
}
func (h *StudentServiceHandler) FindAll(ctx context.Context, req *student.FindAllRequest, resp *student.FindAllResponse) error {
	var tmpStu []*student.Student
	for i, _ := range studentList {
		tmpStu = append(tmpStu, &studentList[i])
	}
	resp.Students = tmpStu
	return nil
}
